//
//  CardLoginViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2017/3/5.
//  Copyright © 2017年 van7ish. All rights reserved.
//

#import "CardLoginViewController.h"

@interface CardLoginViewController ()

/** 头视图 */
@property (nonatomic, strong) UIImageView * headerImageView;
/** 手机图标 */
@property (nonatomic, strong) UIImageView * phoneImageView;
/** 验证码图标 */
@property (nonatomic, strong) UIImageView * idCodeImageView;
/** 手机号输入框 */
@property (nonatomic, strong) UITextField * phoneTextField;
/** 密码输入框 */
@property (nonatomic, strong) UITextField * idCodeTextField;
/** 获取验证码按钮 */
@property (nonatomic, strong) UIButton * idCodeButton;
/** 登录按钮 */
@property (nonatomic, strong) UIButton * loginButton;
/** 倒计时timer */
@property (nonatomic, strong) NSTimer * timer;
/** 倒计时60s */
@property (nonatomic, assign) NSInteger seconds;
/** 返回按钮 */
@property (nonatomic, strong) UIButton * backButton;

@end

@implementation CardLoginViewController

- (UIButton *)idCodeButton{
    if (!_idCodeButton) {
        _idCodeButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(120), self.idCodeTextField.frame.origin.y, WidthScale(100), HeightScale(40))];
        [_idCodeButton setTitle:@"验证" forState:UIControlStateNormal];
        _idCodeButton.titleLabel.font = FONTSIZE(17);
        [_idCodeButton setTitleColor:COLOR_GREEN forState:UIControlStateNormal];
        
        [_idCodeButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        __weak typeof(self) weakSelf = self;
        [_idCodeButton initWithBlock:^(UIButton * idCodeButton) {
            
            if (idCodeButton.enabled) {
                DLog(@"获取验证码");
                [weakSelf requestIDCode];
                
            }
        } for:UIControlEventTouchUpInside];
    }
    return _idCodeButton;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(238)) / 2, SCREEN_H - HeightScale(120), WidthScale(238), HeightScale(61))];
        [_loginButton setImage:ImageNamed(@"login_s") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [_loginButton initWithBlock:^(id obj) {
            DLog(@"登录");
            [weakSelf login];
            
        } for:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (UIButton *)backButton{
    if (!_backButton) {
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
        [_backButton setImage:ImageNamed(@"back") forState:UIControlStateNormal];
        _backButton.transform = CGAffineTransformMakeRotation(-M_PI_2);
        __weak typeof(self)weakSelf = self;
        [_backButton initWithBlock:^(id obj) {
            DLog(@"返回");
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        } for:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (UITextField *)idCodeTextField{
    if (!_idCodeTextField) {
        _idCodeTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneTextField.frame.origin.x, CGRectGetMaxY(self.phoneTextField.frame) + HeightScale(30), self.phoneTextField.frame.size.width, self.phoneTextField.frame.size.height)];
        _idCodeTextField.placeholder = @"验证码";
        _idCodeTextField.font = FONTSIZE(17);
        
        UIImageView *underLine = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(20), CGRectGetMaxY(_idCodeTextField.frame), SCREEN_W - WidthScale(40), 0.5)];
        underLine.image = ImageNamed(@"fengexian");
        _idCodeTextField.secureTextEntry = YES;
        _idCodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self.view addSubview:underLine];
    }
    return _idCodeTextField;
}

-(UIImageView *)idCodeImageView{
    if (!_idCodeImageView) {
        _idCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.phoneImageView.frame.origin.x, CGRectGetMaxY(self.phoneTextField.frame) + HeightScale(40), WidthScale(14), HeightScale(16))];
        _idCodeImageView.image = ImageNamed(@"lock-icon");
    }
    return _idCodeImageView;
}

- (UITextField *)phoneTextField{
    if (!_phoneTextField) {
        _phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.phoneImageView.frame) + WidthScale(15), CGRectGetMaxY(self.headerImageView.frame) + HeightScale(40), SCREEN_W - WidthScale(180), HeightScale(40))];
        _phoneTextField.placeholder = @"输入手机号";
        _phoneTextField.font = FONTSIZE(17);
        _phoneTextField.enabled = NO;
        _phoneTextField.text = self.phoneNumber;
        
        UIImageView *underLine = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(20), CGRectGetMaxY(_phoneTextField.frame), SCREEN_W - WidthScale(40), 0.5)];
        underLine.image = ImageNamed(@"fengexian");
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self.view addSubview:underLine];
    }
    return _phoneTextField;
}

- (UIImageView *)phoneImageView{
    if (!_phoneImageView) {
        _phoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(40), CGRectGetMaxY(self.headerImageView.frame) + HeightScale(40) + HeightScale(10), WidthScale(11.5), HeightScale(18))];
        _phoneImageView.image = ImageNamed(@"number");
    }
    return _phoneImageView;
}

- (UIImageView *)headerImageView{
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W / 2)];
        _headerImageView.image = ImageNamed(@"background");
        _headerImageView.userInteractionEnabled = YES;
    }
    return _headerImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    [self.view addSubview:self.headerImageView];
    [self.view addSubview:self.phoneImageView];
    [self.view addSubview:self.phoneTextField];
    [self.view addSubview:self.idCodeImageView];
    [self.view addSubview:self.idCodeTextField];
    [self.view addSubview:self.idCodeButton];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.backButton];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H - [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
    }];
    
    
    [Tool setNavigationBarType:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc{
    DLog(@"%s", __func__);
}


#pragma mark - data request

- (void)login{
    
    NSString *URL = [NSString stringWithFormat:KcardLogin, KHostAddress, self.cardNumber, self.idCodeTextField.text, self.cardPwd];
    
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        
        DLog(@"%@", responseObject);
        
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            
            [ZRProgressHUD showMsgWithoutView:@"登录成功"];
            
            self.idCodeTextField.text = @"";
            
            [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:[responseObject objectForKey:@"data"]];
            
            //字典序列化并存储到NSUserDefaults
            NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:[responseObject objectForKey:@"data"]];
            
            [[NSUserDefaults standardUserDefaults] setObject:userData forKey:@"user"];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
            
        } else {
            
            [ZRProgressHUD showMsgWithoutView:@"登录失败, 请检查手机号和密码"];
            
        }
        
    } failure:^(NSError *error) {
        
        DLog(@"登录失败 %@", error);
        
    }];
}

/** 获取短信验证码 */
- (void)requestIDCode{
    if ([Tool isMobileNumber:self.phoneTextField.text]) {
        
        NSString *URL = [NSString stringWithFormat:@"%@/services/Users/getSMSCode?registrationCode=%@", KHostAddress, self.cardNumber];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"%@", responseObject);
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                [ZRProgressHUD showMsgWithoutView:@"验证码已发送到您的手机"];
                [_idCodeButton setTitle:@"已发送" forState:UIControlStateDisabled];
                [_idCodeButton setTitleColor:COLOR_FONTLIGHTGRAY forState:UIControlStateDisabled];
                
                self.seconds = 60;
                self.idCodeButton.enabled = NO;
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCountdown:) userInfo:nil repeats:YES];
        
            } else {
                [ZRProgressHUD showMsgWithoutView:[responseObject objectForKey:@"data"]];
            }
        } failure:^(NSError *error) {
            DLog(@"获取验证码失败");
        }];
    } else {
        [ZRProgressHUD showMsgWithoutView:@"请输入正确的手机号码"];
    }
}

/** NSTimer selector */
- (void)timerCountdown:(NSTimer *)timer{
    if (self.seconds) {
        [self.idCodeButton setTitle:[NSString stringWithFormat:@"已发送(%lds)", (long)self.seconds] forState:UIControlStateDisabled];
        self.seconds -= 1;
        DLog(@"倒计时 %ld", self.seconds);
    } else {
        [self.idCodeButton setTitle:[NSString stringWithFormat:@"已发送"] forState:UIControlStateDisabled];
        self.idCodeButton.enabled = YES;
        [self.timer invalidate];
        self.timer = nil;
        
    }
    
}

@end
